package com.ssdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssdp.dto.Result;
import com.ssdp.entity.Voucher;
import com.ssdp.mapper.VoucherMapper;
import com.ssdp.entity.SeckillVoucher;
import com.ssdp.service.ISeckillVoucherService;
import com.ssdp.service.IVoucherService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static com.ssdp.constant.RedisConstant.SECKILL_STOCK_KEY;

/**
 * @author syo 2319615164@qq.com
 * @description 优惠券服务
 * @date 2024/3/14
 * @Copyright syo
 */
@Service
@RequiredArgsConstructor
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {

    private final ISeckillVoucherService seckillVoucherService;

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺的优惠券信息
     * @param shopId 店铺Id
     * @return 优惠券信息
     */
    @Override
    public Result queryVoucherOfShop(Long shopId) {
        // 查询优惠券信息
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
        // 返回结果
        return Result.ok(vouchers);
    }

    /**
     * 添加秒杀优惠券（操作两张表需要添加业务）
     * @param voucher 优惠券信息
     */
    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 1. 保存优惠券
        save(voucher);

        // 2. 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);

        // 3. 保存到redis
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucher.getStock().toString());
    }
}
